import 'package:flutter/material.dart';

enum AnimatedLoopMode { repeat, reverse }

class AnimatedLoop extends StatefulWidget {
  final bool loop;
  final AnimatedLoopMode mode;
  final Curve curve;
  final Duration? duration;
  final Duration? reverseDuration;
  final Widget Function(Animation<double> animation, Widget? child) builder;
  final Widget? child;

  const AnimatedLoop({
    super.key,
    required this.builder,
    this.child,
    this.duration,
    this.reverseDuration,
    this.curve = Curves.fastOutSlowIn,
    this.loop = true,
    this.mode = AnimatedLoopMode.repeat,
  });

  @override
  State<AnimatedLoop> createState() => _AnimatedLoopState();
}

class _AnimatedLoopState extends State<AnimatedLoop> with SingleTickerProviderStateMixin {
  late final AnimationController controller;
  late final Animation<double> animation;

  @override
  void initState() {
    controller = AnimationController(duration: widget.duration, reverseDuration: widget.reverseDuration, vsync: this);
    animation = CurvedAnimation(parent: controller, curve: widget.curve);
    if (widget.loop) {
      controller.addStatusListener((status) {
        if (status == AnimationStatus.completed) controller.repeat(reverse: widget.mode == AnimatedLoopMode.reverse);
      });
    }
    controller.forward();
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => AnimatedBuilder(animation: animation, builder: (context, child) => widget.builder(animation, child), child: widget.child);
}
